<template>
    <view class="login-container" :class="{'mobile': isMobile, 'dark': isDarkMode}">
		<!-- 更新品牌区域 -->
		<view class="auth-side" v-if="!isMobile">
			<view class="side-content">
				<image src="/static/logo-white.png" class="brand-logo" mode="aspectFit" />
				<text class="brand-title">欢迎来到萌友次元</text>
				<text class="brand-desc">在这里，用你的专属虚拟形象<br>连接每一个有趣的灵魂</text>
				<image src="/static/new-illustration.png" class="side-img" mode="aspectFit" />
			</view>
		</view>
        <!-- 右侧表单 -->
        <view class="auth-form-wrapper" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
            <view class="login-card">
            <view class="form-tabs">
                <button
                    class="tab-item"
                    :class="{active: currentTab==='login'}"
                    @tap="switchTab('login')"
                >登录</button>
                <button
                    class="tab-item"
                    :class="{active: currentTab==='register'}"
                    @tap="switchTab('register')"
                >注册</button>
            </view>
                <form v-if="currentTab==='login'" class="form-content" @submit.prevent="handleLogin">
                <view class="form-group">
                    <label for="login-email" class="form-label">邮箱</label>
                    <view class="input-wrapper">
                        <uni-icons type="mail" size="18" class="input-icon"></uni-icons>
                        <input
                            id="login-email"
                            v-model="loginForm.email"
                            type="text"
                            class="form-input"
                            placeholder="请输入邮箱"
                        />
                    </view>
                    <text v-if="loginErrors.email" class="error-message">{{loginErrors.email}}</text>
                </view>
                <view class="form-group">
                    <label for="login-password" class="form-label">密码</label>
                    <view class="input-wrapper">
                        <uni-icons type="lock" size="18" class="input-icon"></uni-icons>
                        <input
                            id="login-password"
                            v-model="loginForm.password"
                            :type="showLoginPassword ? 'text' : 'password'"
                            class="form-input"
                            placeholder="请输入密码"
                        />
                        <uni-icons
                            :type="showLoginPassword ? 'eye-filled' : 'eye-slash-filled'"
                            size="18"
                            class="toggle-password"
                            @click="showLoginPassword = !showLoginPassword"
                        ></uni-icons>
                    </view>
                    <text v-if="loginErrors.password" class="error-message">{{loginErrors.password}}</text>
                </view>
                <view class="form-actions">
                    <view class="remember-me">
                        <checkbox 
                            :checked="loginForm.rememberMe"
                            @change="loginForm.rememberMe = !loginForm.rememberMe"
                            class="checkbox"
                            color="#7B68EE"
                        />
                        <text class="checkbox-label">记住我</text>
                    </view>
                    <text class="forgot-password" @tap="handleForgotPassword">忘记密码？</text>
                </view>
                <button type="button" class="btn-primary" :disabled="isLoading" @click="handleLogin">
                    <template v-if="isLoading">
                        <uni-icons type="spinner-cycle" size="20" class="loading-icon"></uni-icons>
                        <text>登录中...</text>
                    </template>
                    <template v-else>登录</template>
                </button>
                <view class="divider"><text>或</text></view>
                <view class="social-login">
                    <button class="social-btn wechat" @tap="handleWxLogin">
                        <uni-icons type="weixin" size="18"></uni-icons>
                        <text class="social-text">微信登录</text>
                    </button>
                    <button class="social-btn qq" @tap="handleQqLogin">
                        <uni-icons type="qq" size="18"></uni-icons>
                        <text class="social-text">QQ登录</text>
                    </button>
                </view>
            </form>
                <RegisterForm v-else :switchTab="switchTab" @view-terms="handleViewTerms" @view-privacy="handleViewPrivacy" />
            </view>
        </view>
    </view>
</template>

<script>
import { login, register } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { validateLoginForm, validateRegisterForm } from '../../utils/validation'
import { handleRegister as registerHandler } from '../../utils/registerHandler'
import RegisterForm from './RegisterForm.vue'

export default {
    components: {
        RegisterForm
    },
    data() {
        return {
            currentTab: 'login',
            isLoading: false,
            showLoginPassword: false,
            showRegisterPassword: false,
            showConfirmPassword: false,
            loginForm: {
                email: '',
                password: '',
                rememberMe: false
            },
            registerForm: {
                name: '',
                email: '',
                password: '',
                confirmPassword: '',
                agreeTerms: false
            },
            loginErrors: {},
            registerErrors: {},
            isMobile: false,
            isDarkMode: false,
            // 手势滑动相关数据
            touchStartX: 0,
            touchEndX: 0,
            // 键盘高度检测
            keyboardHeight: 0
        }
    },
    mounted() {
        const systemInfo = uni.getSystemInfoSync();
        this.isMobile = systemInfo.windowWidth < 768;
        this.isDarkMode = systemInfo.theme === 'dark';
        // 检查是否有保存的登录信息
        const savedEmail = uni.getStorageSync('savedEmail')
        if (savedEmail) {
            this.loginForm.email = savedEmail
            this.loginForm.rememberMe = true
        }
        
        // 监听键盘高度变化 (仅在App平台支持)
        // #ifdef APP-PLUS
        if (this.isMobile) {
            uni.onKeyboardHeightChange(res => {
                this.keyboardHeight = res.height;
            });
        }
        // #endif
    },
    methods: {
        switchTab(tab) {
            this.currentTab = tab
            this.loginForm = { email: '', password: '', rememberMe: false }
            this.registerForm = { name: '', email: '', password: '', confirmPassword: '', agreeTerms: false }
            this.loginErrors = {}
            this.registerErrors = {}
            this.showLoginPassword = false
            this.showRegisterPassword = false
            this.showConfirmPassword = false
        },
        async handleLogin() {
            if (this.isLoading) return; // 防止重复点击
            
            this.loginErrors = validateLoginForm(this.loginForm);
            if (Object.keys(this.loginErrors).length > 0) {
                return;
            }
            
            this.isLoading = true;
            try {
                const response = await login({
                    email: this.loginForm.email,
                    password: this.loginForm.password
                });
                
                if (!response || !response.token) {
                    throw new Error('登录响应无效');
                }

                // 保存登录信息
                   if (this.loginForm.rememberMe) {
                    uni.setStorageSync('savedEmail', this.loginForm.email);
                } else {
                    uni.removeStorageSync('savedEmail');
                }

                // 更新用户状态
                const userStore = useUserStore();
                // 设置用户信息到状态管理
                userStore.setUserInfo({
                        userId: parseInt(response.user_id, 10),
                        userName: response.user_name,
                        avatar: response.avatar || '',
                        token: response.token,
                        role: response.role || ''
                    });

                    // 保存userId到本地存储
                      // 检查登录响应中的用户ID字段
                      // 输出完整登录响应调试
                      console.log('登录响应数据:', response);
                      const userId = response.id || response.user_id || response.userId;
                      if (!userId) {
                        console.error('登录响应中未找到用户ID');
                        uni.showToast({ title: '登录失败', icon: 'error' });
                        return;
                      }
                      uni.setStorageSync('userId', parseInt(userId, 10));
                      uni.showToast({ 
                        title: '登录成功', 
                        icon: 'success',
                    duration: 1500
                });

                setTimeout(() => {
                    uni.reLaunch({
                        url: '/pages/home/home'
                    });
                }, 1500);

            } catch (error) {
                console.error('登录失败:', error);
                uni.showToast({ 
                    title: error.message || '登录失败，请重试', 
                    icon: 'none'
                });
            } finally {
                this.isLoading = false;
            }
        },
        async handleRegister() {
            await registerHandler({
                registerForm: this.registerForm,
                setRegisterErrors: (errs) => { this.registerErrors = errs },
                setLoading: (val) => { this.isLoading = val },
                register,
                validateRegisterForm,
                switchTab: this.switchTab,
                uni
            })
        },
        handleForgotPassword() {
            uni.showToast({ title: '功能开发中', icon: 'none' })
        },
        handleViewTerms() {
            uni.showToast({ title: '功能开发中', icon: 'none' })
        },
        handleViewPrivacy() {
            uni.showToast({ title: '功能开发中', icon: 'none' })
        },
        handleWxLogin() {
            uni.showToast({ title: '微信登录开发中', icon: 'none' })
        },
        handleQqLogin() {
            uni.showToast({ title: 'QQ登录开发中', icon: 'none' })
        },
        // 手势滑动处理函数
        handleTouchStart(e) {
            if (!this.isMobile) return;
            this.touchStartX = e.touches[0].clientX;
        },
        handleTouchMove(e) {
            if (!this.isMobile) return;
            this.touchEndX = e.touches[0].clientX;
        },
        handleTouchEnd() {
            if (!this.isMobile) return;
            const deltaX = this.touchStartX - this.touchEndX;
            const deltaY = Math.abs(e.touches[0].clientY - this.touchStartY);
            
            // 确保是水平滑动且滑动距离足够
            if (Math.abs(deltaX) > 50 && deltaY < 30) {
                if (deltaX > 0 && this.currentTab === 'login') {
                    this.switchTab('register');
                } else if (deltaX < 0 && this.currentTab === 'register') {
                    this.switchTab('login');
                }
            }
        }
    }
}
</script>

<style src="./login.css"></style>